package com.kdg.thread.consurrenttest;

import java.util.concurrent.*;

/**
 * @author kdg
 * @description:
 * @date 2018/5/13.
 */
public class CyclicBarrierDemo {

    public static class Soldier implements Runnable{
        private String soldier;
        private final CyclicBarrier cyclic;

        public Soldier(String soldier, CyclicBarrier cyclic) {
            this.soldier = soldier;
            this.cyclic = cyclic;
        }

        @Override
        public void run() {
            try {
                //等待所有士兵到齐
                cyclic.await();
                doWork();
                //等待所有士兵完成动作
                cyclic.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }

        private void doWork() {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(soldier+" has finished Work");
        }
    }

    public static class BarrierRun implements Runnable{

        private boolean flag;
        private int N;

        public BarrierRun(boolean flag, int n) {
            this.flag = flag;
            N = n;
        }

        @Override
        public void run() {
            if(flag){
                System.out.println("士兵"+N+"个,任务已完成");
            }else{
                System.out.println("士兵"+N+"个,集合完毕");
                flag = true;
            }
        }
    }

    public static void main(String[] args) {
        final int N=10;
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(N, N, 0L,
                TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
        boolean flag = false;
        CyclicBarrier cyclicBarrier = new CyclicBarrier(N, new BarrierRun(flag, N));
        System.out.println("集合队伍！！！");
        for(int i=0;i<N;i++){
            System.out.println("士兵"+i+"报道");
            threadPoolExecutor.submit(new Soldier("士兵"+i,cyclicBarrier));
        }
    }
}
